import sys
import os
from PyQt5.QtWidgets import QApplication, QDialog, QListWidget
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QIcon
import pandas as pd
from PyQt5.QtCore import QTime

from .Ui_sys_config import Ui_SysConfig
import pts.global_variable as glv
from ..setting import SETTINGS, SETTING_FILENAME
from ..utility import save_json

class SysConfig(QDialog, Ui_SysConfig):
    file_gnfundflow1 = r'Data\gnfundflow1.csv'
    file_GNblockGD = r'Data\GNblockGD.txt'
    file_GNblockPC = r'Data\GNblockPC.txt'

    file_hyfundflow1 = r'Data\hyfundflow1.csv'
    file_HYblockGD = r'Data\HYblockGD.txt'
    file_HYblockPC = r'Data\HYblockPC.txt'

    def __init__(self):
        super(SysConfig, self).__init__()
        self.setupUi(self)

        # 板块配置发生改变
        self.hasChanged1 = False
        # 系统配置发生改变
        self.hasChanged2 = False
        self.initUi()

        self.listHYBlockAll.itemDoubleClicked.connect(self.on_listHYBlockAll_itemDoubleClicked)
        self.listHYBlockGD.itemDoubleClicked.connect(self.on_listHYBlockGD_itemDoubleClicked)
        self.listHYBlockPC.itemDoubleClicked.connect(self.on_listHYBlockPC_itemDoubleClicked)

        self.listGNBlockAll.itemDoubleClicked.connect(self.on_listGNBlockAll_itemDoubleClicked)
        self.listGNBlockGD.itemDoubleClicked.connect(self.on_listGNBlockGD_itemDoubleClicked)
        self.listGNBlockPC.itemDoubleClicked.connect(self.on_listGNBlockPC_itemDoubleClicked)

        self.spinBlockNumber.valueChanged.connect(self.on_hasChanged2_Changed)

        self.timeOpen1.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timeClose1.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timeOpen2.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timeClose2.timeChanged.connect(self.on_hasChanged2_Changed)

        self.spPZ_1.valueChanged.connect(self.on_hasChanged2_Changed)
        self.spPZ_2.valueChanged.connect(self.on_hasChanged2_Changed)
        self.spPZ_3.valueChanged.connect(self.on_hasChanged2_Changed)
        self.spPZ_4.valueChanged.connect(self.on_hasChanged2_Changed)
        self.spPZ_5.valueChanged.connect(self.on_hasChanged2_Changed)
        self.spPZ_6.valueChanged.connect(self.on_hasChanged2_Changed)

        self.timePH_1.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timePH_2.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timePH_3.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timePH_4.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timePH_5.timeChanged.connect(self.on_hasChanged2_Changed)
        self.timePH_6.timeChanged.connect(self.on_hasChanged2_Changed)

        # 默认切换到的页面
        self.tabWidget.setCurrentIndex(2)

    def initListBlocGDPC(self):
        self.listHYBlockGD.addItems(glv.gHYBlockGD)
        self.listHYBlockPC.addItems(glv.gHYBlockPC)
        self.listGNBlockGD.addItems(glv.gGNBlockGD)
        self.listGNBlockPC.addItems(glv.gGNBlockPC)

    def initUi(self):
        '''初始化界面'''
        # 设置窗口的图标
        self.setWindowIcon(QIcon(r'images\YuLan.png'))

        if not os.path.exists(self.file_gnfundflow1):
            return

        stock_data = pd.read_csv(self.file_hyfundflow1)
        block_listGN = list(stock_data['名称'])
        for block_name in block_listGN:
            self.listHYBlockAll.addItem(block_name)

        stock_data = pd.read_csv(self.file_gnfundflow1)
        block_listGN = list(stock_data['名称'])
        for block_name in block_listGN:
            self.listGNBlockAll.addItem(block_name)

        self.spinBlockNumber.setValue(SETTINGS["block.number"])

        # 任务配置
        # 开盘时间
        ti = QTime.fromString(SETTINGS["RW.timeOpen1"])
        self.timeOpen1.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timeClose1"])
        self.timeClose1.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timeOpen2"])
        self.timeOpen2.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timeClose2"])
        self.timeClose2.setTime(ti)

        # 盘中任务
        self.spPZ_1.setValue(SETTINGS["RW.spPZ_1"])
        self.spPZ_2.setValue(SETTINGS["RW.spPZ_2"])
        self.spPZ_3.setValue(SETTINGS["RW.spPZ_3"])
        self.spPZ_4.setValue(SETTINGS["RW.spPZ_4"])
        self.spPZ_5.setValue(SETTINGS["RW.spPZ_5"])
        self.spPZ_6.setValue(SETTINGS["RW.spPZ_6"])

        # 盘后任务
        ti = QTime.fromString(SETTINGS["RW.timePH_1"])
        self.timePH_1.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timePH_2"])
        self.timePH_2.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timePH_3"])
        self.timePH_3.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timePH_4"])
        self.timePH_4.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timePH_5"])
        self.timePH_5.setTime(ti)
        ti = QTime.fromString(SETTINGS["RW.timePH_6"])
        self.timePH_6.setTime(ti)

    def addStock(self, listA: QListWidget, listB: QListWidget):
        item = listA.currentItem()
        if item is None:
            return

        stockName = item.text()
        for i in range(listB.count()):
            if stockName == listB.item(i).text():
                return
        listB.addItem(stockName)

        self.hasChanged1 = True

    def delStock(self, listB: QListWidget):
        index = listB.currentRow()
        if index < 0:
            return
        item = listB.item(index)
        listB.takeItem(index)
        del item

        self.hasChanged1 = True

    def ListToDomain(self):
        glv.gHYBlockGD = []
        for i in range(self.listHYBlockGD.count()):
            glv.gHYBlockGD.append(self.listHYBlockGD.item(i).text())
        str = ','.join(glv.gHYBlockGD)
        with open(self.file_HYblockGD, 'w', encoding='utf-8') as f:
            f.write(str)

        glv.gHYBlockPC = []
        for i in range(self.listHYBlockPC.count()):
            glv.gHYBlockPC.append(self.listHYBlockPC.item(i).text())
        str = ','.join(glv.gHYBlockPC)
        with open(self.file_HYblockPC, 'w', encoding='utf-8') as f:
            f.write(str)

        glv.gGNBlockGD = []
        for i in range(self.listGNBlockGD.count()):
            glv.gGNBlockGD.append(self.listGNBlockGD.item(i).text())
        str = ','.join(glv.gGNBlockGD)
        with open(self.file_GNblockGD, 'w', encoding='utf-8') as f:
            f.write(str)

        glv.gGNBlockPC = []
        for i in range(self.listGNBlockPC.count()):
            glv.gGNBlockPC.append(self.listGNBlockPC.item(i).text())
        str = ','.join(glv.gGNBlockPC)
        with open(self.file_GNblockPC, 'w', encoding='utf-8') as f:
            f.write(str)

    def SaveSetting(self):
        SETTINGS["block.number"] = self.spinBlockNumber.value()

        SETTINGS["RW.timeOpen1"] = self.timeOpen1.time().toString("HH:mm")
        SETTINGS["RW.timeClose1"] = self.timeClose1.time().toString("HH:mm")
        SETTINGS["RW.timeOpen2"] = self.timeOpen2.time().toString("HH:mm")
        SETTINGS["RW.timeClose2"] = self.timeClose2.time().toString("HH:mm")

        SETTINGS["RW.spPZ_1"] = self.spPZ_1.value()
        SETTINGS["RW.spPZ_2"] = self.spPZ_2.value()
        SETTINGS["RW.spPZ_3"] = self.spPZ_3.value()
        SETTINGS["RW.spPZ_4"] = self.spPZ_4.value()
        SETTINGS["RW.spPZ_5"] = self.spPZ_5.value()
        SETTINGS["RW.spPZ_6"] = self.spPZ_6.value()

        SETTINGS["RW.timePH_1"] = self.timePH_1.time().toString("HH:mm")
        SETTINGS["RW.timePH_2"] = self.timePH_2.time().toString("HH:mm")
        SETTINGS["RW.timePH_3"] = self.timePH_3.time().toString("HH:mm")
        SETTINGS["RW.timePH_4"] = self.timePH_4.time().toString("HH:mm")
        SETTINGS["RW.timePH_5"] = self.timePH_5.time().toString("HH:mm")
        SETTINGS["RW.timePH_6"] = self.timePH_6.time().toString("HH:mm")

        save_json(SETTING_FILENAME, SETTINGS)

    @pyqtSlot()
    def on_btnExit_clicked(self):
        '''退出'''
        if self.hasChanged1:
            self.ListToDomain()
        if self.hasChanged2:
            self.SaveSetting()
        self.close()

    # 以下为行业板块配置的槽函数

    @pyqtSlot()
    def on_btnHYAddGD_clicked(self):
        self.addStock(self.listHYBlockAll, self.listHYBlockGD)

    @pyqtSlot()
    def on_listHYBlockAll_itemDoubleClicked(self):
        self.addStock(self.listHYBlockAll, self.listHYBlockGD)

    @pyqtSlot()
    def on_btnHYDelGD_clicked(self):
        self.delStock(self.listHYBlockGD)

    @pyqtSlot()
    def on_listHYBlockGD_itemDoubleClicked(self):
        self.delStock(self.listHYBlockGD)

    @pyqtSlot()
    def on_btnHYAddPC_clicked(self):
        self.addStock(self.listHYBlockAll, self.listHYBlockPC)

    @pyqtSlot()
    def on_btnHYDelPC_clicked(self):
        self.delStock(self.listHYBlockPC)

    @pyqtSlot()
    def on_listHYBlockPC_itemDoubleClicked(self):
        self.delStock(self.listHYBlockPC)

    # 以下为概念板块配置的槽函数

    @pyqtSlot()
    def on_btnGNAddGD_clicked(self):
        self.addStock(self.listGNBlockAll, self.listGNBlockGD)

    @pyqtSlot()
    def on_listGNBlockAll_itemDoubleClicked(self):
        self.addStock(self.listGNBlockAll, self.listGNBlockGD)

    @pyqtSlot()
    def on_btnGNDelGD_clicked(self):
        self.delStock(self.listGNBlockGD)

    @pyqtSlot()
    def on_listGNBlockGD_itemDoubleClicked(self):
        self.delStock(self.listGNBlockGD)

    @pyqtSlot()
    def on_btnGNAddPC_clicked(self):
        self.addStock(self.listGNBlockAll, self.listGNBlockPC)

    @pyqtSlot()
    def on_btnGNDelPC_clicked(self):
        self.delStock(self.listGNBlockPC)

    @pyqtSlot()
    def on_listGNBlockPC_itemDoubleClicked(self):
        self.delStock(self.listGNBlockPC)

    # 以下为系统配置的槽函数

    @pyqtSlot()
    def on_hasChanged2_Changed(self):
        self.hasChanged2 = True


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = SysConfig()
    ui.show()
    sys.exit(app.exec_())
